package org.atovio.eh.handler;

import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理类。
 * 1. 需要使用@ControllerAdvice 或 @RestControllerAdvice注解
 * @author AtoVio, Winter Yuan
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // 定义方法处理   数学异常
    @ExceptionHandler(ArithmeticException.class)
    public String handlerArithmeticException(ArithmeticException e, Model model) {
        String msg = e.getMessage();
        model.addAttribute("msg", msg);
        return "exception";
    }

    // 处理JSR303 验证参数的异常
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Map<String,Object> handlerJSR303Exception(BindException e) {

        System.out.println("=== 打标记 ===");

        Map<String , Object> map = new HashMap<>();
        BindingResult br = e.getBindingResult();

        if (br.hasErrors()) {
            List<FieldError> errors = br.getFieldErrors();

            for (int i = 0, len = errors.size(); i < len; i ++) {
                FieldError error = errors.get(i);
                map.put(i + "-" + error.getField(), error.getDefaultMessage());
            }
        }

        return map;
    }
}
